import { MyProcessDesigner, MyProcessPenal } from "@/components/bpmnProcessDesigner/package";
// 自定义元素选中时的弹出菜单（修改 默认任务 为 用户任务）
import CustomContentPadProvider from "@/components/bpmnProcessDesigner/package/designer/plugins/content-pad";
// 自定义左侧菜单（修改 默认任务 为 用户任务）
import CustomPaletteProvider from "@/components/bpmnProcessDesigner/package/designer/plugins/palette";
import { modelGet, updateModelBpmn } from "@/api/bpm/model";
import { useLocation, useNavigate } from "react-router-dom";
import { useMessage } from "@/hooks/web/useMessage";
import { useEffect, useState } from "react";
import "./index.less";
import { getUrlParams } from "@/utils";

export default function ModelEditor() {
	const navigate = useNavigate(); // 路由
	const { state, search } = useLocation();
	const queryState = state ? state : search ? getUrlParams(search) : { modelId: "" };

	const { createMessage } = useMessage(); // 国际化

	const [xmlString, setXmlString] = useState(undefined); // BPMN XML
	const [modeler, setModeler] = useState(null); // BPMN Modeler
	const controlForm = {
		simulation: true,
		labelEditing: false,
		labelVisible: false,
		prefix: "flowable",
		headerButtonSize: "mini",
		additionalModel: [CustomContentPadProvider, CustomPaletteProvider]
	};
	const [model, setModel] = useState(); // 流程模型的信息

	/** 初始化 modeler */
	const initModeler = item => {
		setTimeout(() => {
			// modeler.value = item
			setModeler(item);
		}, 10);
	};

	/** 关闭按钮 */
	const close = () => {
		navigate("/bpm/manager/model");
	};

	/** Request */

	const getModelXml = async () => {
		if (!queryState.modelId) {
			createMessage.error("缺少模型 modelId 编号");
			return;
		}
		// 查询模型
		const data = await modelGet({ id: queryState.modelId });
		if (!data.bpmnXml) {
			// 首次创建的 Model 模型，它是没有 bpmnXml，此时需要给它一个默认的
			data.bpmnXml = ` <?xml version="1.0" encoding="UTF-8"?>
        <definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.activiti.org/processdef">
          <process id="${data.key}" name="${data.name}" isExecutable="true" />
          <bpmndi:BPMNDiagram id="BPMNDiagram">
            <bpmndi:BPMNPlane id="${data.key}_di" bpmnElement="${data.key}" />
          </bpmndi:BPMNDiagram>
        </definitions>`;
		}
		setModel({
			...data,
			bpmnXml: undefined // 清空 bpmnXml 属性
		});
		setXmlString(data.bpmnXml);
	};

	/** 添加/修改模型 */
	const save = async (bpmnXml: string) => {
		const data = {
			...model,
			bpmnXml: bpmnXml // bpmnXml 只是初始化流程图，后续修改无法通过它获得
		};
		try {
			// 提交
			await updateModelBpmn(data);
			createMessage.success(data.id ? "edit success!" : "save success!");
		} catch (err) {
			createMessage.error(data.id ? "edit fail!" : "save fail!");
		}

		// 跳转回去
		close();
	};

	/** Effect */

	useEffect(() => {
		getModelXml();
	}, []);

	return (
		<div className="modelEditor relative">
			{xmlString !== undefined && (
				<MyProcessDesigner
					key="designer"
					value={xmlString}
					{...controlForm}
					keyboard
					initFinished={initModeler}
					additionalModel={controlForm.additionalModel}
					save={save}
				/>
			)}
			{/* <!-- 流程属性器，负责编辑每个流程节点的属性 --> */}
			<MyProcessPenal
				key="penal"
				bpmnModeler={modeler as any}
				prefix={controlForm.prefix}
				className="process-panel"
				model={model}
			/>
		</div>
	);
}
